#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode* head = nullptr, * tail = nullptr;
        while (l1 || l2)
        {
            int sum = 0;
            if (l1)
                sum += l1->val;
            if (l2)
                sum += l2->val;
            if (head == nullptr)
            {
                sum += carry;
                head = new ListNode(sum % 10);
                carry = sum / 10;
                tail = head;
                tail->next = nullptr;
            }
            else
            {
                sum += carry;
                ListNode* tmp = new ListNode(sum % 10);
                carry = sum / 10;
                tmp->next = nullptr;
                tail->next = tmp;
                tail = tmp;
            }
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;
        }
        if (carry)
        {
            ListNode* tmp = new ListNode(carry);
            tmp->next = nullptr;
            tail->next = tmp;
            tail = tmp;
        }
        return head;
    }
};